$(function(){
    /**
     * 页面初始化
     */
    function init(){

    	bindEvent();
        //表单的JQueryValidater配置验证---jquery.validate插件验证法
        $("#myForm").validate(validateInfo);
    }

    /**
     * 事件绑定
     */
    function bindEvent(){
    	//修改商品信息
    	$('#save').click(function() {
    		updateGoods();
    	});
    	//返回
    	$('#back').click(function() {			 
            window.history.go(-1);
    	});

        //辅图上传
        $("#myForm .side-image").change(function(){
            var i= $(this).parents(".side-image-wrap").index();
            var deleteImg = $("#deleteImg").val();
            if(deleteImg){
                $("#deleteImg").val(deleteImg+','+i);
            }
            else{
                $("#deleteImg").val(i);
            }
        });

        //辅图删除
        $("#myForm .delete-slide-image").click(function(){
            var img = $(this).attr("data-img");
            var gid = $(this).attr("data-gid");
            var that = this;
            if(img){
            	$.ajax({
					type:'post',
					url:'deleteImg',
					data:{
						img:img,
						gid:gid
					},
					dataType:'json',
					success:function(res){
						if(res.errorCode==0){
							$(that).parent().remove();
						}
					}
				})
			}
        });

        /**
         * 删除 商品属性组合
         */
        $("#myForm .property-group .delete").click(function(){
            if($("#myForm .property-group").length == 1){
                //至少保留一个属性组合
                responseTip(1,"很抱歉，操作失败，至少要保留一组商品属性！",2000);
            }else{
                var _this = $(this);
                var gpid = _this.attr("data-gpid");//表goodsproperty主键id
                $.ajax({
                    type:"post",
                    url:"deleteGoodsProperty",
                    data:{"gpid":gpid},
                    dataType:"json",
                    success:function(json,statusText){
                        if(json.errorCode == 0){
                            _this.parents(".property-group").remove();
                        }else{
                            responseTip(json.errorCode,json.errorInfo,1500);
                        }
                    },
                    error:errorResponse
                })
            }
        });
        
        /**
         * 重新选择模板
         */
        $("#myForm .reset-property").click(function(){
        	 myConfirmModal("重新选择模板将会删除所有当前属性,确定操作吗？",function(){
        		 $(".property-group-area .property-group").addClass('deleted');
        		 $("#myForm #is_reset").val(1);
        		 $("#tid").removeAttr('disabled');
        		 $(".add-property-group-wrap").removeClass('hidden');
        		 $("#tid .old-tid").remove();
        		 $(".add-property-group-wrap .property-group-add-tips").addClass('hidden');
        		 $("#tid").change();
             });
        });
        
        //添加属性
        $(".add-property-group-wrap .property-group-add").click(function(){
			if(!$(".content .form-inline").prop("disabled")){
				var new_group = $(".property-tr .property-group-wrap .property-group:not(.deleted)").eq(0).clone();
				new_group.find('input').val('');
				new_group.find('select option').removeAttr('selected');
				new_group.append("<a href='javascript:;' class='btn btn-danger btn-xs property-group-delete'>删除</a>");
				$(".property-tr .property-group-wrap").append(new_group);
			}else{
				var tid = $(".content #tid").val();
        		$.ajax({
        			async:false,
        			url:"../AssembleTemplate/findPropertyList",
	                type:"post",
	                data:{"tid":tid},
	                dataType:"json",
	                beforeSend:function(xhr){
	                    //显示“加载中。。。”
	                    $("#loading").modal('show');
	                },
	                complete:function(){
	                    //隐藏“加载中。。。”
	                    $("#loading").modal('hide');
	                },
	                success:function(json,statusText){
	                    if(json.errorCode == 0){
	                    	$(".property-tr").removeClass('hidden');
	                    	var html = '<div class="property-group add-item">';
	                    	var myList = json.data;
	                    	for(var i = 0; i < myList.length;i++){
	                    		var obj = myList[i];
	                    		var optionList =  obj.list;
	                    		var option_html = "";
	                    		for(var j=0; j < optionList.length; j++){
	                    			var option = optionList[j];
	                    			option_html += "<option value="+option.value+">"+option.value+"</option>";
	                    		}
	                    		html += '<span class="span property">'
	                    					+'<span  class="property-name">'+obj.name+'</span>'
	                    					+'<select class="property-value">'
	                    						+option_html
	                    					+'</select>'
	                    				+'</span>';	
	                    	}
	                    	html += '<span class="span">'
	                    			+'<span>单买价</span>'
	                    			+'<input type="text" class="oriprice">'
	                    			+'</span>'
	                    			+'<span class="span">'
	                    			+'<span>拼团价</span>'
	                    			+'<input type="text" class="price">'
	                    			+'</span>'
	                    			+'<span class="span">'
	                    				+'<span>库存</span>'
	                    				+'<input type="text" class="inventory">'
	                    			+'</span>'
	                    			+'<a href="javascript:;" class="btn btn-danger btn-xs property-group-delete">删除</a>'
	                    		+'</div>';
	                    	if(myList.length == 0){
	                    		$("#tid").val('');
	                    		responseTip(1,"此模板无属性,请在模板列表中重新设置", 3000);
	                    		$(".property-tr .property-group-wrap .property-group").append('');
	                    		$(".property-tr").addClass('hidden');
	                    		
	                    	}else{
	                    		$(".property-tr .property-group-wrap").append(html);
	                    		$("#inventory").val(0);
	                    		$("#inventory").parents('tr').addClass('hidden');
	                    		$("#standard").val(1);
	                    	}
	                    }else{
	                        responseTip(1,json.errorInfo);
	                    }
	                },
	                error:errorResponse
        		});
			}
        	
			$(".property-group .property-group-delete").click(function(){
    			$(this).parents('.property-group').remove();
    		});
		});
        
        //选择商品规格
        $("#tid").change(function(){
        	if($(this).val() != ''){
        		$(".property-tr").removeClass('hidden');
        		var tid = $(this).val();
        		$.ajax({
        			 url:"../AssembleTemplate/findPropertyList",
	                type:"post",
	                data:{"tid":tid},
	                dataType:"json",
	                beforeSend:function(xhr){
	                    //显示“加载中。。。”
	                    $("#loading").modal('show');
	                },
	                complete:function(){
	                    //隐藏“加载中。。。”
	                    $("#loading").modal('hide');
	                },
	                success:function(json,statusText){
	                    if(json.errorCode == 0){
	                    	$(".property-tr").removeClass('hidden');
	                    	var html = '<div class="property-group">';
	                    	var myList = json.data;
	                    	for(var i = 0; i < myList.length;i++){
	                    		var obj = myList[i];
	                    		var optionList =  obj.list;
	                    		var option_html = "";
	                    		for(var j=0; j < optionList.length; j++){
	                    			var option = optionList[j];
	                    			option_html += "<option value="+option.value+">"+option.value+"</option>";
	                    		}
	                    		html += '<span class="span property">'
	                    					+'<span  class="property-name">'+obj.name+'</span>'
	                    					+'<select class="property-value">'
	                    						+option_html
	                    					+'</select>'
	                    				+'</span>';	
	                    	}
	                    	html += '<span class="span">'
	                    			+'<span>单买价</span>'
	                    			+'<input type="text" class="oriprice">'
	                    			+'</span>'
	                    			+'<span class="span">'
	                    			+'<span>拼团价</span>'
	                    			+'<input type="text" class="price">'
	                    			+'</span>'
	                    			+'<span class="span">'
	                    				+'<span>库存</span>'
	                    				+'<input type="text" class="inventory">'
	                    			+'</span>'
	                    		+'</div>';
	                    	if(myList.length == 0){
	                    		$("#tid").val('');
	                    		responseTip(1,"此模板无属性,请在模板列表中重新设置", 3000);
	                    		$(".property-tr .property-group-wrap .property-group").html('');
	                    		$(".property-tr").addClass('hidden');
	                    	}else{
	                    		$(".property-tr .property-group-wrap .property-group:not(.deleted)").remove();
	                    		$(".property-tr .property-group-wrap").append(html);
	                    		$("#inventory").val(0);
	                    		$("#inventory").parents('tr').addClass('hidden');
	                    		$("#standard").val(1);
	                    	}
	                    }else{
	                        responseTip(1,json.errorInfo);
	                    }
	                },
	                error:errorResponse
        		});
        	}else{
        		$(".property-tr .property-group-wrap .property-group:not(.deleted)").html('');
        		$(".property-tr").addClass('hidden');
        		$("#inventory").val('');
        		$("#inventory").parents('tr').removeClass('hidden');
        		$("#standard").val(0);
        	}
        });

        
    }

    /**
     * 修改商品
     */
    function updateGoods(){
    	//商品规格，0: 统一规格 1: 多规格
        var standard = $("#myForm #standard").val();
        if(standard == 1){
	        //获取所有属性组合，判断是否合法
	    	var addGroups = [];//当前模板增加属性组合
	        var groups = [];//用来存储所有的属性组合相关值
	        var groupsElem = $("#myForm .property-group");
	        for(var i = 0;i < groupsElem.length; i++){
	            var group = {};//存储当前组合的相关值
	            var price = $(".price",groupsElem[i]).val().trim();//现价
	            var prevPrice = $(".price",groupsElem[i]).attr("data-price");//先前的现价
	            var isPriceChange = (price == prevPrice)?false:true;//价格是否修改
	            var oriprice = $(".oriprice",groupsElem[i]).val().trim();//原价
	            var inventory = $(".inventory",groupsElem[i]).val().trim();//库存
	            var gpid = $(".price",groupsElem[i]).parent().attr("data-gpid");//表mall_goodsproperty主键id
	            
	            if(price == "" || oriprice == "" || inventory == ""){
	                if($("#myForm .property-info label").length == 0){
	                    $("#myForm .property-info").html('<label for="name" generated="true" class="error">请设置所有值</label>');
	                }
	                return false;
	            }else{
	                $("#myForm .property-info label").remove();
	            }
	            
	            var propertList = [];
	            var propertyListElem = $(".property",groupsElem[i]);
	            for(var j = 0;j < propertyListElem.length; j++){
	                var property = {};//存储属性值
	                var name = $(".property-name",propertyListElem[j]).text();
	                var value = $(".property-value",propertyListElem[j]).val();
	                property = {"name":name,"value":value};
	                propertList.push(property);
	            }
	            //判断是否增加新的属性
	            if($(groupsElem[i]).hasClass("add-item")){
	                var addGroup = {
	                        "price":price,
	                        "oriprice":oriprice,
	                        "inventory":inventory,
	                        "propertyList":propertList
	                    };
	                    addGroups.push(addGroup);
	            }else{
	            	group = {
	                        "gpid":gpid,
	                        "price":price,
	                        "isPriceChange":isPriceChange,
	                        "oriprice":oriprice,
	                        "inventory":inventory,
	                        "propertyList":propertList
	                };
	                groups.push(group);
	            }
	        }
	        $("#myForm #propertyGroups").val(JSON.stringify(groups));
	        if($("#myForm .property-group.add-item").length > 0){
	        	$("#myForm #addGroups").val(JSON.stringify(addGroups));
	            $("#myForm #addProperty").val(1);//模板不变的情况下增加属性
	        }
	        $("#tid").prop('disabled',false);
	    }
        $("#myForm").ajaxSubmit($.extend(true,{},formOptions,goodsFormOptions));
    }
    /**
     * 提交添加商品信息的表单配置
     */
    var  goodsFormOptions={
        url:'updateGoods',
        success:successResponse,
        error:errorResponse
    };
    /**
     * 添加商品信息得到服务器响应的回调方法
     */
    function successResponse(json,statusText){
        if(json.errorCode == 0){
            responseTip(json.errorCode,"恭喜您，操作成功！",1500,function(){window.history.go(-1);});

        }else{
            responseTip(json.errorCode,json.errorInfo,1500);
        }
    }

    //表单验证信息
    var validateInfo ={
        rules:{
            name:{//商品名称
                required:true
            },
            price:{//商品现价
                required:true,
                goodsPrice:true,
            },
            ori_price:{//原价
                required:true,
                goodsPrice:true,
            },
            inventory:{//库存
                required:true,
                digits:true
            },
            sort_num:{
                required:true
            },
            imgurl:{
                accept:"jpg,jpeg,gif,png"
            },
            simple_desc:{//简述
                required:true
            }
        },
        messages:{
            name:{//商品名称
                required:"必填项"
            },
            price:{//商品标准价格
                required:"必填项",
                goodsPrice:"价格由数字组成,最多包含两位小数",
            },
            ori_price:{//商品标准价格
                required:"必填项",
                goodsPrice:"价格由数字组成,最多包含两位小数",
            },
            inventory:{//库存
                required:"必填项",
                digits:"库存为整数"
            },
            sort_num:{
                required:"必填项"
            },
            imgurl:{
                accept:"仅支持jpg、jpeg、gif、png格式"
            },
            simple_desc:{//商品简述
                required:"必填项"
            }
        },
        errorPlacement:function(error,element){
            element.parent().next().append(error);
        }
    };
    init();
});